package com.whately.core.base.thumb;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;

public class ImageUtils {
    private final static Logger log = LoggerFactory.getLogger(ImageUtils.class);

    private final static int  descSize = 200 ; //500K


   /* public static void generateFixedSizeImage(String from ,String to ,int w,int h){
        try {
            Thumbnails.of(from).scale(0.5f).outputQuality(0.42f).toFile(to);
            Thumbnails.of(from).size(w,h).toFile(to);
        } catch (IOException e) {
            log.error("generateFixedSizeImage error " ,e);
        }
    }*/

    public static void main(String[] args) throws Exception {
        String from = "/Users/qinchao/Downloads/IMG_1017.PNG";
        String to = "/Users/qinchao/Downloads/IMG_1017-bak04.PNG";
        byte[] b = IOUtils.toByteArray(new FileInputStream(from));
        byte[] c = generateFixedSizeImageAndCompress(b);
        IOUtils.write(c,new FileOutputStream(to));
    }

    public static byte[] generateFixedSizeImageAndCompress(byte[] originalByteData ){
        byte[] buf = null;
        try {
            buf = compressPicCycle(originalByteData,descSize);
        } catch (IOException e) {
            log.error("generateFixedSizeImage error " ,e);
        }
        return buf;
    }

    public static byte[] generateFixedSizeImage(byte[] originalByteData ,  int w, int h){
        byte[] buf = null;
        try {
            InputStream originalIns = new ByteArrayInputStream(originalByteData);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            // Thumbnails.of(originalIns).scale(1.00f).outputQuality(0.42f).toOutputStream(outputStream);
            Thumbnails.of(originalIns).size(w,h).toOutputStream(outputStream);
            buf = outputStream.toByteArray();
        } catch (IOException e) {
            log.error("generateFixedSizeImage error " ,e);
        }
        return buf;
    }


    /**
     * @Description: 压缩图片到指定大小
     * @Param:  desFileSize：大小，accuracy：每次缩小几倍
     * @return:  String
     * @Author: zzy
     * @Date: 2019/9/29
     */
    public static byte[] compressPicCycle(byte[] bytes) throws IOException {
        return compressPicCycle(bytes,descSize);
    }

    private static byte[] compressPicCycle(byte[] bytes, long desFileSize) throws IOException {
        double accuracy = 0.5d;
        long srcFileSizeJPG = bytes.length;
        System.out.println(srcFileSizeJPG);
        // 2、判断大小，如果小于，不压缩；如果大于等于，压缩
        if (srcFileSizeJPG <= desFileSize * 1024) {
            return bytes;
        }
        // 计算宽高
        BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes));
        int srcWdith = bim.getWidth();
        int srcHeigth = bim.getHeight();
        int desWidth = new BigDecimal(srcWdith).multiply(
                new BigDecimal(accuracy)).intValue();
        int desHeight = new BigDecimal(srcHeigth).multiply(
                new BigDecimal(accuracy)).intValue();

        ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流（写入到内存）
        Thumbnails.of(new ByteArrayInputStream(bytes)).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(baos);
        byte[] bytes1 = baos.toByteArray();
        baos.close();
        return compressPicCycle(bytes1, desFileSize);
    }



    /**
     * url获取图片流
     * @return
     */
    public static byte[] loadImageBytes(String urlString) {
        URL url;
        byte[] data=null;
        try {
            url = new URL(urlString);
            data = IOUtils.toByteArray(url);
        } catch (MalformedURLException e) {
            log.error("loadImageInputStream MalformedURLException " ,e);
        } catch (Exception e) {
            log.error("loadImageInputStream Exception " ,e);
        }
        return data;
    }


    /**
     * 读取 本地文件，转为字节数组
     * @param path 本地文件路径
     * @return
     * @throws IOException
     */
    /*public static byte[] getImage(String path) throws IOException{
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(path));
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);

        byte[] temp = new byte[2048];
        int size = 0;
        while ((size = in.read(temp)) != -1) {
            out.write(temp, 0, size);
        }
        in.close();
        byte[] content = out.toByteArray();
        return content;
    }*/


}
